package com.jml.装饰模式.五期.异步多渠道群发框架.observer;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@Component
public class JmlSubject {

    /**
     * 类型 ObServer
     */
    private List<ObServer> listObServer = new ArrayList<>();
    /**
     * 线程池
     */
    private ExecutorService executorService;


    public JmlSubject() {
        executorService = Executors.newFixedThreadPool(10);
    }

    /**
     * 新增ObServer
     *
     * @param obServer
     */
    public void addObServer(ObServer obServer) {
        listObServer.add(obServer);
    }

    /**
     * 通知给所有的观察者
     *
     * @param jsonObject
     */
    public void notifyObServer(JSONObject jsonObject) {
        for (ObServer obServer : listObServer) {
            // 单独开启线程异步通知
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    obServer.sendMsg(jsonObject);
                }
            });

        }
    }

}
